import Vue from 'vue'
import VueRouter from 'vue-router'
import './enhanceMethod'
import routes from './routes'
import store from '@/store'
import { getToken, removeToken } from '@/utils/token'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  }
})
const arr = ['/trade', '/pay', '/addCar', '/paySuccess']
router.beforeEach(async (to, from, next) => {
  const token = getToken()
  if (token) {
    const { id } = store.state.user.userList
    if (id) {
      next()
    } else {
      try {
        // 调用 actions 获取用户信息
        await store.dispatch('user/userInformation')

        // 尝试获取用户信息，如果获取成功，直接放行即可
        next()
      } catch (error) {
        // 执行到 catch ，说明 token 可能失效了
        // 既然失效，需要将 token 进行删除
        removeToken()
        next('/login')
      }
    }
  } else {
    if (arr.includes(to.path)) return next('/login')
    next()
  }
})
export default router
